package cm.geguo.datagramsocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 作者：13687
 * 日期：2017/5/29
 * 项目：Socket
 * 描述：发送和接收
 */
public class UDPDemo {

	public static void main(String[] args) throws IOException, InterruptedException {
		DatagramSocket ds=new DatagramSocket();
		byte[] bytes="Hello udp".getBytes();
		recevie();
		DatagramPacket p=new DatagramPacket(bytes,0,bytes.length,
				InetAddress.getByName("127.0.0.1"),10000);
		Thread.sleep(1000);// 等待接收者上线
		ds.send(p);//并没有制定端口
		ds.close();
	}


	public static void recevie() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					DatagramSocket datagramSocket = null;
					try {
						datagramSocket = new DatagramSocket(10000);
					} catch (SocketException e) {
						e.printStackTrace();
					}
					byte[] buff=new byte[1024];
					DatagramPacket p=new DatagramPacket(buff,buff.length);
					try {
						datagramSocket.receive(p);
					} catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("str="+ new String(p.getData(),0,p.getLength()));
					datagramSocket.close();
				}
			}
		}).start();

	}
}


